/*
 * @lc app=leetcode.cn id=1583 lang=typescript
 *
 * [1583] 统计不开心的朋友
 */

// @lc code=start
function unhappyFriends(n: number, preferences: number[][], pairs: number[][]): number {
  const order = new Array(n).fill(0).map((_) => new Array(n).fill(0));
  // i和j的亲密关系，j约小，亲密关系越大
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n - 1; j++) {
      order[i][preferences[i][j]] = j;
    }
  }

  const match = new Array(n).fill(0);
  // pairs的匹配关系
  for (const [x, y] of pairs) {
    match[x] = y;
    match[y] = x;
  }

  let ans = 0;
  for (let x = 0; x < n; x++) {
    const y = match[x];
    const idx = order[x][y];
    console.log(idx);
    for (let j = 0; j < idx; j++) {
      const u = preferences[x][j];
      const v = match[u];
      if (order[u][x] < order[u][v]) {
        ans++;
        break;
      }
    }
  }

  return ans;
}
// @lc code=end
